﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.CheckManagement
{
    public partial class AddCheckWayForm : DevExpress.XtraEditors.XtraForm
    {
        private long? editId = null;

        public AddCheckWayForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterParent;
            this.Load += AddCheckWayForm_Load;
            btnSubmit.Click += BtnSubmit_Click;
            btnCancel.Click += (s, e) => this.DialogResult = DialogResult.Cancel;
        }

        // 新增/编辑数据回显
        public void SetModel(CheckWay.CheckWayDto model)
        {
            if (model == null) return;
            editId = model.id;
            txtCheckCode.Text = model.checkCode;
            txtCheckWayName.Text = model.checkWayName;
            txtCheckCode.ReadOnly = true;
        }

        private async void AddCheckWayForm_Load(object sender, EventArgs e)
        {
            // 仅新增时自动生成编号
            if (editId == null)
            {
                using (HttpClient client = new HttpClient())
                {
                    var code = await client.GetStringAsync("http://localhost:5295/api/CheckWay/GenerateCheckCode");
                    txtCheckCode.Text = code.Replace("\"", "");
                    txtCheckCode.ReadOnly = true;
                }
            }
        }

        private async void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtCheckWayName.Text))
            {
                MessageBox.Show("请输入检验名称！");
                return;
            }

            var data = new
            {
                id = editId ?? 0, // 新增时为0，编辑时为实际id
                checkCode = txtCheckCode.Text.Trim(),
                checkWayName = txtCheckWayName.Text.Trim()
            };

            string url = editId == null
                ? "http://localhost:5295/api/CheckWay/AddCheckWay"
                : "http://localhost:5295/api/CheckWay/UpdateCheckWay";

            using (HttpClient client = new HttpClient())
            {
                var resp = await client.PostAsJsonAsync(url, data);
                if (resp.IsSuccessStatusCode)
                {
                    MessageBox.Show(editId == null ? "添加成功！" : "修改成功！");
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("操作失败！");
                }
            }
        }

        private void AddCheckWayForm_Load_1(object sender, EventArgs e)
        {

        }

      
    }
}